-- Trap
-- Created by chengb Dec/26/2015
-- 陷阱格子

-- 内部函数声明
local initArrowTrap
local initBloodTrap;
local initCrossbowTrap;
local initCrossTrap;
local initCannonTrap;
local initGlobalTrap;
local initHunterTrap;
local initTrapFireBlade;
local initCannonTrap2;

-- 初始化
function initTrap(self)
    self.isPause = false;

    self.item:removeAllChildren();

    local trapId = self.gridData.id;
    local trapType = CommonTrapM.query(trapId, "type");
    local trapAlias = CommonTrapM.query(trapId, "alias");

    local function launchTrap()
        -- 触发陷阱效果
        local pos = self.gridData:getPos();

        -- 检查一遍
        if not CommonTrapM.checkAction(trapId, pos) then
            local cost = CommonTrapM.query(trapId, "cost") or {};
            if #table.keys(cost) > 0 then
                -- 消耗不足
                local itemId = table.keys(cost)[1];
                local itemName = ItemM.query(itemId, "name")
                alert(string.format(getLocStr("lack_bullet"), itemName));
            end
            return;
        end
        DungeonActionM.go("trap_action", pos);

        -- 发动提示
        local tip = CommonTrapM.query(trapId, "launch_tip");
        if type(tip) == "string" and tip ~= "" then
            alert(tip);
        end
    end

    if trapAlias == "hunter_trap" then
        -- 猎人陷阱
        require "game/ui/form/dungeon/special/UIBeelineTrap"
        initHunterTrap(self, launchTrap);
    elseif trapAlias == "magic_bow" then
        -- 破魔重弩
        initCrossbowTrap(self, launchTrap);
    elseif trapAlias == "gun_trap" then
        -- 土制陷阱
        initCrossTrap(self, launchTrap);
    elseif trapAlias == "ship_gun" then
        -- 排炮
        initCannonTrap(self, launchTrap);
    elseif trapAlias == "fire_blade" then
        -- 炎龙刃
        initTrapFireBlade(self, launchTrap);
    elseif trapAlias == "element_swirl" then
        -- 元素漩涡
        initGlobalTrap(self, launchTrap);
    elseif trapAlias == "blood_trap" then
        -- 血腥陷阱
        initBloodTrap(self, launchTrap);
    elseif trapAlias == "arrow_trap" then
        -- 弩矢陷阱
        require "game/ui/form/dungeon/special/UIBeelineTrap"
        initArrowTrap(self, launchTrap)
    elseif trapAlias == "ship_gun2" then
        -- 排炮2，支持上下左右
        initCannonTrap2(self, launchTrap);
    elseif trapAlias == "time_bomb" then
        -- 定时炸弹
        initTimeBomb(self, launchTrap);
    else
        -- 暂不支持其他类型
        trace("UIGrid", "无法初始化陷阱，暂不支持的陷阱类型 ：" .. tostring(trapType));
    end
end

-- 初始化弩矢陷阱
function initArrowTrap(self, launchFunc)
    if self.gridData.state == GRID_STATE_DISABLE and self.gridData.bonus then
        -- 如果有掉落
        self:initItem(self.gridData);
        return;
    end

    local trapId = self.gridData.id;
    local trapInfo = CommonTrapM.query(trapId);

    assert(type(trapInfo) == 'table', string.format("获取不到陷阱(id=%s)信息。", tostring(trapId)));

    -- 陷阱图标
    local iconPath = getLevelItemIconPath("trap");

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            -- 音效
            AudioM.playFx("equip_unload");

            -- 打开直线型陷阱界面
            local uiForm = UIBeelineTrap.create(self.gridData, launchFunc);
            UIMgr.getCurrentScene():removeFormByName("UIBeelineTrap");
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end

    -- 使用一张透明的图片来接收点击事件
    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setOpacity(0);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);
    self.iconPath = iconPath;

    -- 整体往上偏移一点
    self.item:setPositionY(20);

    -- 旋转箭头方向
    local direction =  self.gridData.direction;
    local angle = 0;
    if direction == "up" then
    -- 上，不需要旋转
    elseif direction == "right" then
        -- 右
        angle = 90;
    elseif direction == "down" then
        -- 下
        angle = 180;
    elseif direction == "left" then
        -- 左
        angle = 270;
    end

    self.icon:setRotation(angle);

    -- 创建弩车模型，初始停留在第1帧
    local animation = createEffectAnim(1154);
    animation:gotoFrameAndPause(0);
    self.animation = animation;
    self.animation:setRotation(angle);

    self.item:addChild(self.animation);
end

-- 初始化猎人陷阱
function initHunterTrap(self, launchFunc)
    if self.gridData.state == GRID_STATE_DISABLE and self.gridData.bonus then
        -- 如果有掉落
        self:initItem(self.gridData);
        return;
    end

    local trapId = self.gridData.id;
    local trapInfo = CommonTrapM.query(trapId);

    assert(type(trapInfo) == 'table', string.format("获取不到陷阱(id=%s)信息。", tostring(trapId)));

    -- 陷阱图标
    local iconPath = getLevelItemIconPath("trap");

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            -- 音效
            AudioM.playFx("equip_unload");

            -- 打开直线型陷阱界面
            local uiForm = UIBeelineTrap.create(self.gridData, launchFunc);
            UIMgr.getCurrentScene():removeFormByName("UIBeelineTrap");
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end

    -- 使用一张透明的图片来接收点击事件
    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setOpacity(0);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);
    self.iconPath = iconPath;

    -- 绘制箭头和弓
    local arowImg = ccui.ImageView:create(getLevelItemIconPath("arow"));
    arowImg:setName("arow");

    -- 整体往上偏移一点
    self.item:setPositionY(20);

    -- 旋转箭头方向
    local direction =  self.gridData.direction;
    local angle = 0;
    if direction == "up" then
        -- 上，不需要旋转
    elseif direction == "right" then
        -- 右
        angle = 90;
    elseif direction == "down" then
        -- 下
        angle = 180;
    elseif direction == "left" then
        -- 左
        angle = 270;
    end

    self.icon:setRotation(angle);
    arowImg:setRotation(angle);

    -- 创建弩车模型，初始停留在第1帧
    local animation = createEffectAnim(1154);
    animation:gotoFrameAndPause(0);
    self.animation = animation;
    self.animation:setRotation(angle);

    self.item:addChild(self.animation);
    self.item:addChild(arowImg);
end

-- 初始破魔重弩陷阱
function initCrossbowTrap(self, launchFunc)
    local trapId = self.gridData.id;
    local trapInfo = CommonTrapM.query(trapId);

    assert(type(trapInfo) == 'table', string.format("获取不到陷阱(id=%s)信息。", tostring(trapId)));

    -- 陷阱图标
    local iconPath = getLevelItemIconPath("rusty_bow2");

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            -- 音效
            AudioM.playFx("equip_unload");

            -- 打开建筑查看界面
            local buttonText = trapInfo.button_text;
            self:openBuildingView(launchFunc, 0, trapInfo.dialog, buttonText, trapInfo.name, iconPath);
        end
    end

    -- 使用一张透明的图片来接收点击事件
    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setOpacity(0);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);
    self.iconPath = iconPath;

    -- 整体往上偏移一点
    self.item:setPositionY(20);

    -- 创建弩车模型，初始停留在第1帧
    local animation = createEffectAnim(1247);
    animation:gotoFrameAndPause(0);
    self.animation = animation;

    self.item:addChild(self.animation);

    -- 绘制箭头
    local arowImg = ccui.ImageView:create(getLevelItemIconPath("rusty_arow"));
    self.item:addChild(arowImg);
    arowImg:setName("arow");

    -- 出现效果
    playBuildingAppearEffect(self, self.item);
end

-- 初始化土制陷阱
function initCrossTrap(self, launchFunc)
    local trapId = self.gridData.id;
    local trapInfo = CommonTrapM.query(trapId);

    assert(type(trapInfo) == 'table', string.format("获取不到陷阱(id=%s)信息。", tostring(trapId)));

    -- 陷阱图标
    local iconPath = getLevelItemIconPath("trap2");

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            local buttonText = trapInfo.button_text;

            -- 获取使用次数
            local dialog = trapInfo["dialog"];
            local curTimes = self.gridData.times or 0;
            local maxTimes = trapInfo["times"];
            dialog = dialog .. string.format(getLocStr("use_times_format"), curTimes, maxTimes);

            -- 音效
            AudioM.playFx("equip_unload");

            -- 打开建筑查看界面
            self:openBuildingView(launchFunc, -10, dialog, buttonText, trapInfo.name, iconPath);
        end
    end

    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);
    self.iconPath = iconPath;

    self.icon:setScale(0.9);

    -- 整体往上偏移一点
    self.item:setPositionY(20);
end

-- 初始化排炮
function initCannonTrap(self, launchFunc)
    local trapId = self.gridData.id;
    local trapInfo = CommonTrapM.query(trapId);

    assert(type(trapInfo) == 'table', string.format("获取不到陷阱(id=%s)信息。", tostring(trapId)));

    local iconPath = getLevelItemIconPath("trap3");

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            local buttonText = trapInfo.button_text;

            -- 获取描述和排炮威力
            local dialog = trapInfo["dialog"];
            local damage = FormulaM.invoke("CALC_CANNON_DAMAGE", trapId, "damage")
            dialog = string.format(dialog, damage);

            -- 音效
            AudioM.playFx("equip_unload");

            -- 打开建筑查看界面
            self:openBuildingView(launchFunc, -10, dialog, buttonText, trapInfo.name, iconPath);
        end
    end

    -- 使用一张透明的图片来接收点击事件
    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setOpacity(0);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);

    -- 创建排炮动画，初始停留在第24帧
    local animation = createEffectAnim(2049);
    animation:gotoFrameAndPause(23);
    self.animation = animation;

    self.item:addChild(self.animation);

    -- 整体往上偏移一点
    self.item:setPositionY(10);
end

-- 初始化炎龙刃
function initTrapFireBlade(self, launchFunc)
    local trapId = self.gridData.id;
    local trapInfo = CommonTrapM.query(trapId);

    assert(type(trapInfo) == 'table', string.format("获取不到陷阱(id=%s)信息。", tostring(trapId)));

    local iconPath = getLevelItemIconPath("fire_blade");

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            local buttonText = trapInfo.button_text;

            -- 获取使用次数
            local dialog = trapInfo["dialog"];

            -- 音效
            AudioM.playFx("admix_medal");

            -- 打开建筑查看界面
            self:openBuildingView(launchFunc, -10, dialog, buttonText, trapInfo.name, iconPath);
        end
    end

    self.item:removeAllChildren();

    -- 使用一张透明的图片来接收点击事件
    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setOpacity(0);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);
    self.item:setPositionY(-5);

    -- 将节点还原到初始状态（炎龙刃可能是在怪死亡的瞬间刷出来的，item节点有可能会被隐藏）
    self.item:setVisible(true);
    self.item:setScale(1);
    self.icon:setScale(1);

    -- 播放吸收特效
    playEffect(self, 1212);

    local function appear()
        -- 创建炎龙刃动画
        local animation = createEffectAnim(1202);
        animation:play(0, 13, true);
        self.animation = animation;

        self.item:addChild(self.animation);

        -- 播放节点弹出特效
        playPopUpAppear(self.item);
    end

    performWithDelay(self, appear, 0.3);
end

-- 初始化元素漩涡
function initGlobalTrap(self, launchFunc)
    local trapId = self.gridData.id;
    local trapInfo = CommonTrapM.query(trapId);

    assert(type(trapInfo) == 'table', string.format("获取不到陷阱(id=%s)信息。", tostring(trapId)));

    -- 陷阱图标
    local iconPath = getLevelItemIconPath("element_swirl");

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            local buttonText = trapInfo.button_text;

            -- 获取使用次数
            local dialog = trapInfo["dialog"];
            local curTimes = self.gridData.times or 0;
            local maxTimes = trapInfo["times"];
            dialog = dialog .. string.format(getLocStr("use_times_format"), curTimes, maxTimes);

            -- 音效
            AudioM.playFx("bee_hit");

            -- 打开建筑查看界面
            self:openBuildingView(launchFunc, -10, dialog, buttonText, trapInfo.name, iconPath);
        end
    end

    -- 使用一张透明的图片来接收点击事件
    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setOpacity(0);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);

    -- 将节点还原到初始状态
    self.item:setVisible(true);
    self.item:setScale(1);
    self.icon:setScale(1);

    -- 播放吸收特效
    playEffect(self, 1212);

    local function appear()
        -- 漩涡特效
        local swirlAnim = createEffectAnim(1207);
        swirlAnim:play(0, 79, true);
        self.swirlAnim = swirlAnim;
        self.item:addChild(swirlAnim);

        -- 闪电特效
        local lightAnim = createEffectAnim(1206);
        lightAnim:play(0, 38, true);
        self.lightAnim = lightAnim;
        self.item:addChild(lightAnim);

        local function callback()
            -- 呼吸动画
            playBubbleAnima(self.item, false);
        end

        -- 播放节点弹出特效
        playPopUpAppear(self.item, callback);
    end

    performWithDelay(self, appear, 0.3);
end

-- 初始化血腥陷阱
function initBloodTrap(self, launchFunc)
    local trapId = self.gridData.id;
    local trapInfo = CommonTrapM.query(trapId);

    assert(type(trapInfo) == 'table', string.format("获取不到陷阱(id=%s)信息。", tostring(trapId)));

    -- 陷阱图标
    local iconPath = getLevelItemIconPath("bloody_trap");

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            local buttonText = trapInfo.button_text;

            -- 获取使用次数
            local dialog = trapInfo["dialog"];

            -- 音效
            AudioM.playFx("equip_unload");

            -- 打开建筑查看界面
            self:openBuildingView(launchFunc, -10, dialog, buttonText, trapInfo.name, iconPath);
        end
    end

    -- 使用一张透明的图片来接收点击事件
    self.icon = ccui.ImageView:create(iconPath);
    --self.icon:setOpacity(0);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);
    self.item:setPositionY(20);

    -- 将节点还原到初始状态
    self.item:setVisible(true);
    self.item:setScale(1);
    self.icon:setScale(1);
end

-- 初始化排炮2（支持上下左右配置）
function initCannonTrap2(self, launchFunc)
    local trapId = self.gridData.id;
    local trapInfo = CommonTrapM.query(trapId);

    assert(type(trapInfo) == 'table', string.format("获取不到陷阱(id=%s)信息。", tostring(trapId)));

    local iconPath = getLevelItemIconPath("trap3");

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            local buttonText = trapInfo.button_text;

            -- 获取描述和排炮威力
            local dialog = trapInfo["dialog"];
            local damage = trapInfo["damage"];
            local damageNum = damage["damage"];
            dialog = string.format(dialog, damage);

            -- 音效
            AudioM.playFx("equip_unload");

            -- 打开建筑查看界面
            self:openBuildingView(launchFunc, -10, dialog, buttonText, trapInfo.name, iconPath);
        end
    end

    -- 使用一张透明的图片来接收点击事件
    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setOpacity(0);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);

    -- 创建排炮动画，初始停留在第24帧
    local animation = createEffectAnim(2049);
    animation:gotoFrameAndPause(23);
    self.animation = animation;

    self.item:addChild(self.animation);

    -- 旋转箭头方向
    local direction =  self.gridData.direction;
    local angle = 0;
    if direction == "up" then
        -- 整体往上偏移一点
        self.item:setPositionY(20);
    elseif direction == "right" then
        -- 右
        angle = 90;
    elseif direction == "down" then
        -- 下
        angle = 180;
    elseif direction == "left" then
        -- 左
        angle = 270;
    end

    self.item:setRotation(angle);
end

-- 初始化定时炸弹
function initTimeBomb(self, launchFunc)
    local trapId = self.gridData.id;
    local trapInfo = CommonTrapM.query(trapId);

    assert(type(trapInfo) == 'table', string.format("获取不到陷阱(id=%s)信息。", tostring(trapId)));

    -- 陷阱图标
    local iconPath = getLevelItemIconPath("time_bomb");

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            local buttonText = trapInfo.button_text;

            -- TODO: 回合数、伤害
            local dialog = trapInfo["dialog"];
            local round = CommonTrapM.getTrapCountDown(self.gridData:getPos());
            local force = FormulaM.invoke("CALC_TIME_BOMB_DAMAGE", trapId, CommonTrapM.query(trapId, key));
            dialog = string.gsub(dialog, "{round}", round)
            dialog = string.gsub(dialog, "{force}", force)

            -- 音效
            AudioM.playFx("equip_unload");

            -- 打开建筑查看界面
            self:openBuildingView(nil, -10, dialog, buttonText, trapInfo.name, iconPath);
        end
    end

    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);
    self.iconPath = iconPath;

    -- 整体往上偏移一点
    -- self.item:setPositionY(20);
end